package com.ch_linghu.dnssettings;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DnssettingsActivity extends Activity {
	Button set_btn;
	EditText dns1_edit, dns2_edit;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
		try {
	        //get DNS
			String dns1 = getDNS(1);
	        String dns2 = getDNS(2);
	        
	        dns1_edit = (EditText)findViewById(R.id.dns1);
	        dns2_edit = (EditText)findViewById(R.id.dns2);
	        dns1_edit.setText(dns1);
	        dns2_edit.setText(dns2);
	        
	        set_btn = (Button)findViewById(R.id.set);
	        set_btn.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					String dns1 = dns1_edit.getText().toString(); 
					String dns2 = dns2_edit.getText().toString();
					
					try {
						setDNS(dns1, 1);
						setDNS(dns2, 2);
					} catch (IOException e) {
						toastMessage(e.getMessage());
						Log.e("DNSSETTINGS", e.getMessage());
					} catch (InterruptedException e) {
						toastMessage(e.getMessage());
						Log.e("DNSSETTINGS", e.getMessage());
					}
					toastMessage("new dns has been setted!");
				}
			});
		} catch (IOException e) {
			// TODO Auto-generated catch block
			toastMessage(e.getMessage());
			Log.e("DNSSETTINGS", e.getMessage());
		}
    }
    
    private void toastMessage(String msg){
		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
    
    private String getDNS(int index) throws IOException{
    	String cmd = String.format("getprop net.dns%d", index);
    	Process p = Runtime.getRuntime().exec(cmd);
	 	BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    	StringBuilder sb = new StringBuilder();
    	String line;
		while((line = in.readLine()) != null){
			sb.append(line);
		}
		return sb.toString();
    }
    
    private boolean setDNS(String ip, int index) throws IOException, InterruptedException {
    	String cmd = String.format("setprop net.dns%d %s", index, ip);
    	Process p = Runtime.getRuntime().exec("su");

    	// Attempt to write a file to a root-only   
    	DataOutputStream os = new DataOutputStream(p.getOutputStream());   
    	os.writeBytes(cmd + "\n");  
     
    	//Close the terminal  
    	os.writeBytes("exit\n");   
    	os.flush();   

    	p.waitFor();   
    	if (p.exitValue() != 255) {   
    		return true;  
    	}else{
    		return false;
    	}
    }
}